package com.funcas.frule.core.engine.impl;

import com.funcas.frule.core.adapter.BaseAdapter;
import com.funcas.frule.core.engine.IRuleEngine;
import com.funcas.frule.core.engine.RuleEntity;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by FUNCAS on 2014/9/13.
 */
public class RuleEngine implements IRuleEngine{

    private Logger log = LoggerFactory.getLogger(RuleEngine.class);
    private RuleEntity ruleEntity;
    ClassLoader parent = RuleEngine.class.getClassLoader();
    GroovyClassLoader loader = new GroovyClassLoader(parent);

    GroovyObject groovyObject = null;

    private void prepareRuleEnv() throws IllegalAccessException, InstantiationException {
        String shell = ruleEntity.getShell();

        Class<?> groovyClass = loader.parseClass(shell);
        groovyObject = (GroovyObject) groovyClass.newInstance();
        for(String key : this.ruleEntity.getRuleVariables().keySet()){
            groovyObject.setProperty(key,this.ruleEntity.getRuleVariables().get(key));
        }
        log.debug("-> " + groovyObject.getClass().getName());
    }

    /**
     * 执行所有规则集
     *
     * @return
     */
    @Override
    public Object fireAllRules() throws InstantiationException, IllegalAccessException {
        prepareRuleEnv();
        return groovyObject.invokeMethod("run", null);
    }

    /**
     * 按名称执行单条规则集
     *
     * @param methodName
     * @return
     */
    @Override
    public Object fireRuleByName(String methodName,Object[] params) throws InstantiationException, IllegalAccessException {
        prepareRuleEnv();
        return groovyObject.invokeMethod(methodName, params);
    }

    /**
     * 设置适配器
     *
     * @param adapter
     */
    @Override
    public void setAdapter(BaseAdapter adapter) {
        this.ruleEntity = adapter.getRuleEntity();
    }
}
